<template>
  <!-- 应急预案管理 -->
  <div class="emerPlan">
    <basic-container>
      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :page.sync="page"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 v-model="form"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.plan_delete" @click="handleDelete">删 除</el-button>
          <el-button type="warning" size="small" icon="el-icon-download" plain v-if="permission.plan_export" @click="handleExport">导出</el-button>
          <el-button type="primary" size="small" icon="el-icon-delete-solid" plain @click="handleVoid">作 废</el-button>
        </template>

        <!-- 发布 -->
        <template slot="fbgl" slot-scope="scope">
          <div v-if="scope.row['ywzt'] === 2">
            <el-form label-width="0px">
              <el-button type="primary" size="small" @click="publishPlan(scope.row['id'])" plain>发布</el-button>
            </el-form>
          </div>
          <div v-if="scope.row['ywzt'] === 3">
            <el-button type="success" size="small" plain>已发布</el-button>
          </div>
          <span v-if="scope.row['ywzt'] === 0 || scope.row['ywzt'] === 1 || scope.row['ywzt'] === 9">-</span>
        </template>

        <!-- 预案附件表格自定义 -->
        <template slot="yafj" slot-scope="scope">
          <div class="enclosure_div">
            <a :href="downloadHead + scope.row['yafj']">
              <i class="el-icon-download"></i>下载附件
            </a>
          </div>
        </template>

        <!-- 预案附件表单自定义 -->
        <template slot="yafjForm">
          <div>
            <el-upload action="/api/fileManager/upload/file" :headers="SetHeaders" :file-list="yafjFileList" :before-upload="beforeUploadYAFJ" :on-remove="handleRemoveYAFJ" :on-success="uploadYAFJSuccess">
              <el-button size="small" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </template>

        <!-- 预案类型表格自定义 -->
        <template slot="yalx" slot-scope="scope">
          <div>{{yalx(scope.row)}}</div>
        </template>

        <!-- 适用部门表格自定义 -->
        <template slot="sybm" slot-scope="scope">
          <div>{{sybm(scope.row)}}</div>
        </template>

        <!-- 发布实施日期表格自定义 -->
        <template slot="fbssrq" slot-scope="scope">
          <div>{{fbssrq(scope.row)}}</div>
        </template>

        <!-- 关联危险源-->
        <template slot="idsLabel">
          <span style="color:#F56C6C">*</span><span>关联危险源:</span>
        </template>
        <template slot="idsForm">
          <el-form label-width="0px">
            <el-button type="success" size="small" @click="handleHazard">选择 危险源</el-button>
            <span v-if="hazardTagsErr" class="hazard_error">请选择危险源</span>
            <div class="hazard_point_list">
              <el-tag :key="index" v-for="(tag, index) in hazardTags" closable :disable-transitions="false" @close="closeHazardTag(index)">{{tag.zdwxybh}}</el-tag>
            </div>
          </el-form>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="status" slot-scope="scope">
          <span>{{formatStatus(scope.row)}}</span>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approval" slot-scope="scope">
          <div>
            <el-button v-if="scope.row['ywzt'] === 0" type="success" size="mini" @click="handleApproval(scope.row)">审 批</el-button>
            <span v-else>-</span>
          </div>
        </template>

        <!-- 变更表格自定义 -->
        <template slot="modify" slot-scope="scope">
          <div>
            <el-button v-if="scope.row['ywzt'] === 2" type="primary" size="mini" @click="handleModify(scope.row)">变 更</el-button>
            <el-button v-if="scope.row['ywzt'] === 2" type="warning" size="mini" @click="handleModifyRecord(scope.row)">变更记录</el-button>
            <span v-if="scope.row['ywzt'] !== 2">-</span>
          </div>
        </template>

      </avue-crud>

      <!-- 关联危险源弹窗 -->
      <el-dialog title="关联 危险源" :visible.sync="dialogHazard" append-to-body @close='closeDialog' width="1200px" class="hazardManager">
        <avue-crud :option="hazardOption"
                   :table-loading="hazardLoading"
                   :data="hazardData"
                   :page.sync="hazardPage"
                   ref="hazardCrud"
                   @search-change="hazardSearchChange"
                   @search-reset="hazardSearchReset"
                   @selection-change="hazardSelectionChange"
                   @current-change="hazardCurrentChange"
                   @size-change="hazardSizeChange">
        </avue-crud>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="chooseHazard()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 审批、变更弹窗 -->
      <el-dialog
        :title="dialogTitle"
        append-to-body
        :visible.sync="updateDialog"
        :close-on-click-modal="false"
        :before-close="closeUpdateDialog"
        width="60%"
        class="approval_modify_dialog">
        <!-- 内容 -->
        <avue-form
          ref="updateForm"
          v-model="updateObj"
          :option="updateOption"
          @submit="confirmApprovalModify">

          <!-- 附件表单自定义 -->
          <template slot="yafj">
            <div>
              <el-upload
                v-if="updateDialogType === modifyStr"
                action="/api/fileManager/upload/file"
                :headers="SetHeaders"
                :file-list="bgfjFileList"
                :before-upload="beforeUploadBGFJ"
                :on-remove="handleRemoveBGFJ"
                :on-success="uploadBGFJSuccess">
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-document">
                  选择文件
                </el-button>
              </el-upload>
              <a v-else-if="updateDialogType !== modifyStr && bgfjFileList && bgfjFileList.length > 0"
                 v-for="(item, index) in bgfjFileList"
                 :key="index"
                 :href="downloadHead + item.response.data.id"
                 style="color:#409EFF">
                <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
              </a>
              <span v-else>-</span>
            </div>
          </template>

          <!-- 自定义按钮 -->
          <template slot="menuForm">
            <el-button
              size="small"
              icon="el-icon-close"
              @click="closeUpdateDialog()">
              取 消
            </el-button>
          </template>

        </avue-form>
      </el-dialog>

      <!-- 变更记录弹窗 -->
      <el-dialog
        title="变更记录"
        append-to-body
        :visible.sync="modifyRecordDialog"
        :close-on-click-modal="false"
        :before-close="closeModifyRecordDialog"
        width="60%"
        class="modify_record_dialog"
      >

        <!-- 表格内容 -->
        <avue-crud
          :option="modifyRecordOption"
          :table-loading="modifyRecordLoading"
          :data="modifyRecordData"
          :page.sync="modifyRecordPage"
          v-model="modifyRecordForm"
        >
        </avue-crud>

        <!-- 按钮 -->
        <div class="modify_record_footer">
          <el-button
            type="primary"
            size="small"
            @click="closeModifyRecordDialog()">
            确 定
          </el-button>
        </div>
      </el-dialog>

    </basic-container>
  </div>
</template>

<script>
  import {
    getList,
    getDetail,
    add,
    update,
    remove,
    getYalxList,
    getHazardSList,
    getSybmList,
    getYabhByCustom,
    planPublish,
    invalidPlan,
    getPlanStatus, approvalStatus, modifyPlan, getModifyRecordList
  } from "@/api/emer/plan";
  import {getDeptList} from "@/api/mmhi/major_dangerous_sources";
  import {getToken} from "@/util/auth";
  import {mapGetters} from "vuex";

  const tenantId = JSON.parse(localStorage.getItem("saber-tenantId")).content;

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          refreshBtn: true,
          columnBtn: true,
          calcHeight: 30,
          dialogWidth: 950,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "企业名称",
              prop: "qymc",
              align: "center",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "预案编号",
              prop: "yabh",
              width:130,
              align: "center",
              search: true,
              readonly:true
            },
            {
              label: "预案名称",
              prop: "yamc",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入预案名称",
                trigger: "blur"
              }]
            },
            {
              label: "预案日期",
              prop: "yarq",
              width:100,
              align: "center",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "请输入预案日期",
                trigger: "click"
              }]
            },
            {
              label: "预案类型",
              prop: "yalx",
              align: "center",
              multiple: true,
              type: "tree",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_plan_yalx",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择预案类型",
                trigger: "click"
              }]
            },
            {
              label: "预案级别",
              prop: "yajb",
              type: "select",
              align: "center",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_plan_yajb",
              props: {
                label: "dictValue",
                value: "dictKey"
              }
            },
            {
              label: "适用部门",
              prop: "sybm",
              width:100,
              align: "center",
              type:"tree",
              multiple: true,
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择适用部门",
                trigger: "click"
              }]
            },
            {
              label: "编写人",
              prop: "bxr",
              align: "center",
              maxlength:50,
              rules: [{
                required: true,
                message: "请输入编写人",
                trigger: "blur"
              }]
            },
            {
              label: "编写部门",
              prop: "bxbm",
              width:100,
              align: "center",
              type:"tree",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请选择编写部门",
                trigger: "click"
              }]
            },
            {
              label: "审批人",
              prop: "spr",
              align: "center",
              maxlength:50,
              rules: [{
                required: true,
                message: "请输入审批人",
                trigger: "blur"
              }]
            },
            {
              label: "预案附件",
              prop: "yafj",
              align: "center",
              span: 24,
              width:100,
              slot: true,
              formslot: true,
              viewDisplay: false,
              rules: [
                {
                  required: true,
                  message: "请选择预案附件",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "发布实施日期",
              prop: "fbssrq",
              align: "center",
              width: 100,
              slot: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false
            },
            {
              label: "危险源关联",
              prop: "zdwxybh",
              align: "center",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              hide: true
            },
            {
              label: "关联危险源",
              prop: "ids",
              align: "center",
              hide: true,
              viewDisplay: false,
              formslot:true,
              labelslot:true
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              hide: true
            },
            {
              label: "状态",
              display: false,
              prop: "status",
              align: "center",
              width: 100,
              slot: true
            },
            {
              label: "审批",
              display: false,
              prop: "approval",
              align: "center",
              width: 100,
              slot: true
            },
            {
              label: "变更",
              display: false,
              prop: "modify",
              align: "center",
              width: 180,
              slot: true
            },
            {
              label: "发布管理",
              width: "120px",
              prop: "fbgl",
              slot: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              hide: false,
              align: "center"
            },
            {
              label: "企业id",
              prop: "bladeDeptId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "租户id",
              prop: "tenantId",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建人",
              prop: "createUser",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建部门",
              prop: "createDept",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false
            }
          ]
        },
        data: [],

        dialogHazard: false,
        hazardQuery: {},
        hazardLoading: true,
        hazardPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        hazardSelectionList: [],
        hazardOption: {
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          menu: false,
          addBtn: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          refreshBtn: false,
          columnBtn: false,
          column: [
            {
              label: "危险源编号",
              prop: "zdwxybh",
              align: "center"
            },
            {
              label: "危险源名称",
              prop: "zdwxymc",
              align: "center",
              search: true
            }
          ]
        },
        hazardData: [],
        hazardTags: [],
        hazardTagsErr: false,
        selectHazard: {},

        // 预案类型
        yalxList: {},
        //适用部门
        sybmList: {},

        // 附件
        yafjFileList: [],
        downloadHead: "/api/fileManager/download/",
        SetHeaders: { "Blade-Auth": getToken() },

        //表格状态列
        statusObj: {},

        // 变更附件
        bgfjFileList: [],
        // 审批、变更弹窗
        dialogTitle: "",
        updateObj: {},
        updateDialog: false,
        updateDialogType: "",

        approvalStr: "APPROVAL",
        modifyStr: "MODIFY",

        // 变更记录弹窗
        modifyRecordDialog: false,
        modifyRecordId: "",
        modifyRecordForm: {},
        modifyRecordLoading: true,
        modifyRecordQuery: {},
        modifyRecordData: [],
        modifyRecordPage: {
          pageSize: this.$pageSize,
          currentPage: 1,
          total: 0
        },
        modifyRecordOption: {
          calcHeight: 30,
          tip: false,
          index: false,
          selection: false,
          addBtn: false,
          refreshBtn: false,
          columnBtn: false,
          menu: false,
          column: [
            {
              label: "企业名称",
              prop: "qymc",
              align: "center"
            },
            {
              label: "预案编号",
              prop: "yabh",
              align: "center"
            },
            {
              label: "预案名称",
              prop: "yamc",
              align: "center"
            },
            {
              label: "预案日期",
              prop: "yarq",
              align: "center"
            },
            {
              label: "编写人",
              prop: "bxr",
              align: "center"
            }
          ]
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.plan_add, false),
          viewBtn: this.vaildData(this.permission.plan_view, false),
          delBtn: this.vaildData(this.permission.plan_delete, false),
          editBtn: this.vaildData(this.permission.plan_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      updateOption() {
        return {
          size: "small",
          submitText: "确 定",
          mockBtn: false,
          printBtn: false,
          emptyBtn: false,
          column:  [
            {
              label: "预案编号",
              prop: "yabh",
              align: "center",
              search: true,
              readonly:true
            },
            {
              label: "预案名称",
              prop: "yamc",
              align: "center",
              maxlength:100,
              rules: [{
                required: true,
                message: "请输入预案名称",
                trigger: "blur"
              }]
            },
            {
              label: "预案日期",
              prop: "yarq",
              align: "center",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "请输入预案日期",
                trigger: "click"
              }]
            },
            {
              label: "预案类型",
              prop: "yalx",
              align: "center",
              multiple: true,
              type: "tree",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_plan_yalx",
              props: {
                label: "dictValue",
                value: "dictKey",
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择预案类型",
                trigger: "click"
              }]
            },
            {
              label: "预案级别",
              prop: "yajb",
              type: "select",
              align: "center",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=emer_plan_yajb",
              props: {
                label: "dictValue",
                value: "dictKey"
              }
            },
            {
              label: "适用部门",
              prop: "sybm",
              align: "center",
              type:"tree",
              multiple: true,
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              slot:true,
              rules: [{
                required: true,
                message: "请选择适用部门",
                trigger: "click"
              }]
            },
            {
              label: "编写人",
              prop: "bxr",
              align: "center",
              maxlength:50,
              rules: [{
                required: true,
                message: "请输入编写人",
                trigger: "blur"
              }]
            },
            {
              label: "编写部门",
              prop: "bxbm",
              align: "center",
              type:"tree",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请选择编写部门",
                trigger: "click"
              }]
            },
            {
              label: "审批人",
              prop: "spr",
              align: "center",
              maxlength:50,
              rules: [{
                required: true,
                message: "请输入审批人",
                trigger: "blur"
              }]
            },
            {
              label: "预案附件",
              prop: "yafj",
              align: "center",
              span: 24,
              slot: true,
              formslot: true,
              viewDisplay: false,
              rules: [
                {
                  required: true,
                  message: "请选择预案附件",
                  trigger: "blur"
                }
              ]
            },
            {
              label: "备注",
              prop: "bz",
              align: "center",
              type: "textarea",
              maxlength:500,
              span: 24,
              minRows: 6,
              hide: true
            },
            {
              label: "审批结果",
              prop: "spjg",
              disabled: true,
              type: "radio",
              display: false,
              dicData: [{
                label: "同意",
                value: 1
              }, {
                label: "不同意",
                value: 2
              }],
              rules: [{
                required: true,
                message: "请选择部门审批结果",
                trigger: "change"
              }]
            }
          ]
        }
      }
    },
    mounted() {
      this.initData();
    },
    methods: {
      // 初始化数据
      initData() {
        getDeptList(tenantId).then(res => {
          const column = this.findObject(this.option.column, "sybm");
          const columnA = this.findObject(this.option.column, "bxbm");
          const columnB = this.findObject(this.updateOption.column, "sybm");
          const columnC = this.findObject(this.updateOption.column, "bxbm");
          column.dicData = res.data.data;
          columnA.dicData = res.data.data;
          columnB.dicData = res.data.data;
          columnC.dicData = res.data.data;
        }).then(() => {
          getPlanStatus().then(res => {
            this.statusObj = {};
            res.data.data.forEach(item => {
              this.statusObj[item.dictKey] = item.dictValue;
            });
          }).then(() => {
            this.getYalx();
          }).then(() => {
            this.getSybm();
          });
        });
      },

      // 获取预案类型列表
      getYalx() {
        getYalxList().then(res => {
          this.yalxList = {};
          res.data.data.forEach(item => {
            this.yalxList[item.dictKey] = item.dictValue;
          });
        })
      },
      // 显示预案类型列
      yalx(row) {
        if(row.yalx === undefined || typeof row.yalx === "object") {
          return "";
        }
        let arr =[];
        if(row.yalx.indexOf("|") != -1){
          arr = row.yalx.split("|");
        }else{
          arr = row.yalx.split(",");
        }
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = this.yalxList[arr[i]] === undefined ? arr[i] : this.yalxList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },

      // 获取适用部门列表
      getSybm() {
        getSybmList().then(res => {
          this.sybmList = {};
          res.data.data.forEach(item => {
            this.sybmList[item.id] = item.deptName;
          });
        })
      },
      // 显示适用部门列
      sybm(row) {
        if(row.sybm === undefined || typeof row.sybm === "object") {
          return "";
        }
        let arr =[];
        if(row.sybm.indexOf("|") != -1){
          arr = row.sybm.split("|");
        }else{
          arr = row.sybm.split(",");
        }
        const faults = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = this.sybmList[arr[i]] === undefined ? arr[i] : this.sybmList[arr[i]];
          faults.push(fault);
        }
        return faults.join("|");
      },

      // 显示发布实施日期列
      fbssrq(row) {
        if(row.fbssrq === "") {
          return "-";
        } else {
          return row.fbssrq;
        }
      },

      // 发布应急预案
      publishPlan(id, loading) {
        this.$confirm("确定将选择数据发布?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          planPublish(id).then(() => {
            this.onLoad(this.page);
            this.$message.success("发布成功!");
          }, error => {
            loading();
            window.console.log(error);
          });
        });
      },

      // 格式化状态列
      formatStatus(row) {
        return this.statusObj[row.ywzt];
      },

      // 打开审批弹窗
      handleApproval(row) {
        this.updateDialogType = this.approvalStr;
        this.updateDialog = true;
        this.dialogTitle = "审批应急预案管理";

        const arr =  row.yalx.split("|");
        const arrS = row.sybm.split("|");
        const faults = [];
        const faultAs = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = arr[i];
          faults.push(fault);
        }
        for(let i = 0 ; i < arrS.length ; i++) {
          const faultA = arrS[i];
          faultAs.push(faultA);
        }
        row.yalx = faults.join(",");
        row.sybm = faultAs.join(",");
        this.updateObj = this.formatUpdateForm(row);
        this.bgfjFileList = [];
        if (row.yafj && row.bladeFile && JSON.stringify(row.bladeFile) !== "{}") {
          this.bgfjFileList.push({
            name: row.bladeFile.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: row.bladeFile
            }
          });
        }
        this.updateOption.column.forEach(item => {
          if(item.prop !== "spjg") {
            item.disabled = true;
          }
          if(item.prop === "spjg") {
            item.display = true;
            item.disabled = false;
          }
        });
      },

      // 打开变更弹窗
      handleModify(row) {
        this.updateDialogType = this.modifyStr;
        this.updateDialog = true;
        this.dialogTitle = "变更应急预案管理";

        const arr =  row.yalx.split("|");
        const arrS = row.sybm.split("|");
        const faults = [];
        const faultAs = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = arr[i];
          faults.push(fault);
        }
        for(let i = 0 ; i < arrS.length ; i++) {
          const faultA = arrS[i];
          faultAs.push(faultA);
        }
        row.yalx = faults.join(",");
        row.sybm = faultAs.join(",");

        this.updateObj = this.formatUpdateForm(row);
        this.bgfjFileList = [];
        if (row.yafj && row.bladeFile && JSON.stringify(row.bladeFile) !== "{}") {
          this.bgfjFileList.push({
            name: row.bladeFile.fileName,
            response: {
              code: 200,
              msg: "操作成功",
              success: true,
              data: row.bladeFile
            }
          });
        }
        this.updateOption.column.forEach(item => {
          if (["spr"].includes(item.prop)) {
            item.disabled = true;
          }
          if(item.prop === "spjg") {
            item.display = false;
            item.disabled = true;
          }
        });
      },

      // 格式化审批、变更弹窗表单数据
      formatUpdateForm(row) {
        const data = {};
        for(let key in row) {
          data[key] = row[key];
        }
        return data;
      },

      // 关闭、取消审批&变更弹窗
      closeUpdateDialog() {
        this.updateObj = {};
        this.bgfjFileList = [];
        this.updateDialogType = "";
        this.updateDialog = false;
        this.dialogTitle = "";
      },

      // 确定审批、变更
      confirmApprovalModify() {
        if(this.updateDialogType === this.approvalStr) {
          this.confirmApproval();
        } else if(this.updateDialogType === this.modifyStr) {
          this.confirmModify();
        }
      },

      // 确认审批
      confirmApproval() {
        this.$refs.updateForm.validate((vaild,done)=>{
          if(vaild){
            approvalStatus(this.updateObj.id, this.updateObj.spjg).then(res => {
              if(res.data.success) {
                done();
                this.closeUpdateDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
              }
            });
          }
        })
      },

      //确认变更
      confirmModify(){
        this.$refs.updateForm.validate((vaild,done)=>{
          if(vaild){
            let updateRow = this.formatModifyData(this.updateObj);
            modifyPlan(updateRow).then(res => {
              if(res.data.success) {
                this.closeUpdateDialog();
                this.page.currentPage = 1;
                this.onLoad(this.page);
              }
            });
            done();
          }
        })
      },

      // 获取变更时的数据
      formatModifyData(row) {
        const data = {};
        for(let key in row) {
          data[key] = row[key];
        }
        const arr = row.sybm.split(",");
        const arrS = row.yalx.split(",");
        const faults = [];
        const faultAs = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = arr[i];
          faults.push(fault);
        }
        for(let i = 0 ; i < arrS.length ; i++) {
          const faultA = arrS[i];
          faultAs.push(faultA);
        }
        data["sybm"] = row.sybm = faults.join("|");
        data["yalx"] = row.yalx = faultAs.join("|");
        return data;
      },

      // 打开变更记录弹窗
      handleModifyRecord(row) {
        this.modifyRecordId = row.id;
        this.modifyRecordDialog = true;
        this.modifyRecordPage.currentPage = 1;
        this.modifyRecordOnLoad(this.modifyRecordPage);
      },

      // 获取变更记录列表
      modifyRecordOnLoad(page, params = {}) {
        this.modifyRecordLoading = true;
        this.modifyRecordQuery = {emerPlanId: this.modifyRecordId};
        getModifyRecordList(page.currentPage, page.pageSize, Object.assign(params, this.modifyRecordQuery)).then(res => {
          let resData = res.data.data;
          this.modifyRecordPage.total = resData.total;
          this.modifyRecordData = resData.records;
          this.modifyRecordLoading = false;
        });
      },

      // 确认、取消、关闭变更记录弹窗
      closeModifyRecordDialog() {
        this.modifyRecordDialog = false;
        this.modifyRecordId = "";
      },

      // 打开关联危险源弹窗
      handleHazard() {
        this.dialogHazard = true;
        this.hazardOnLoad(this.hazardPage);
      },

      // 关闭关联危险源弹窗
      closeDialog() {
        this.hazardPage.currentPage = 1;
        this.dialogHazard = false;
        this.hazardSelectionClear();
      },

      // 危险源获取表格数据
      hazardOnLoad(page, params = {}) {
        this.hazardLoading = true;
        getHazardSList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.hazardPage.total = data.total;
          this.hazardData = data.records;
          this.hazardLoading = false;
          if(this.selectHazard !== undefined && JSON.stringify(this.selectHazard) !== "{}" && this.hazardTags.length !== 0) {
            this.$nextTick(() => {
              this.hazardData.forEach(row => {
                if(this.selectHazard[row.id] !== undefined) {
                  this.$refs.hazardCrud.toggleRowSelection(row, true);
                }
              })
            })
          }
        });
      },

      // 危险源清空勾选
      hazardSelectionClear() {
        this.hazardSelectionList = [];
        this.$refs.hazardCrud.toggleSelection();
      },

      // 危险源搜索条件改变事件
      hazardSearchChange(params, done) {
        this.hazardQuery = params;
        this.hazardPage.currentPage = 1;
        this.hazardOnLoad(this.hazardPage, params);
        done();
      },

      // 危险源清空搜索条件
      hazardSearchReset() {
        this.hazardQuery = {};
        this.hazardOnLoad(this.hazardPage);
      },

      // 危险源勾选
      hazardSelectionChange(list) {
        this.hazardSelectionList = list;
      },

      // 危险源换页数
      hazardCurrentChange(currentPage){
        const pageSelectIds = [];
        const pageAllIds = [];
        this.hazardSelectionList.forEach(item => {
          this.selectHazard[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.hazardData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectHazard) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectHazard[id];
          }
        }
        this.hazardPage.currentPage = currentPage;
        this.hazardOnLoad(this.hazardPage);
      },

      // 危险源换每页显示数量
      hazardSizeChange(pageSize){
        this.hazardPage.pageSize = pageSize;
        this.hazardOnLoad(this.hazardPage);
      },

      // 选择危险源
      chooseHazard() {
        const pageSelectIds = [];
        const pageAllIds = [];
        this.hazardSelectionList.forEach(item => {
          this.selectHazard[item.id] = item;
          pageSelectIds.push(item.id);
        });
        this.hazardData.forEach(item => {
          pageAllIds.push(item.id);
        });
        for(let id in this.selectHazard) {
          if(pageSelectIds.indexOf(id) < 0 && pageAllIds.indexOf(id) >= 0) {
            delete this.selectHazard[id];
          }
        }
        if(this.selectHazard === undefined || JSON.stringify(this.selectHazard) === "{}") {
          this.$message.warning("请选择危险源");
          return;
        }
        this.hazardTagsErr = false;
        this.hazardTags = [];
        for(let id in this.selectHazard) {
          this.hazardTags.push(this.selectHazard[id]);
        }
        this.closeDialog();
      },

      // 删除某一个hazard标签
      closeHazardTag(index) {
        this.hazardTags.splice(index, 1);
        if(this.hazardTags.length === 0) {
          this.hazardTagsErr = true;
        }
      },

      rowSave(row, done, loading) {
        if(this.hazardTags.length === 0) {
          this.hazardTagsErr = true;
          loading();
          return;
        }
        delete row.zdwxybh;
        const idsArr = [];
        this.hazardTags.forEach(item => {
          idsArr.push(item.id);
        });
        row.ids = idsArr.join(",");
        row.wxygl = idsArr.join(",");
        row.sybm = typeof row.sybm === "object" ? row.sybm.join("|") : row.sybm;
        row.yalx = typeof row.yalx === "object" ? row.yalx.join("|") : row.yalx;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

      rowUpdate(row, index, done, loading) {
        if(this.hazardTags.length === 0) {
          this.hazardTagsErr = true;
          loading();
          return;
        }
        const arr = row.sybm.split(",");
        const arrS = row.yalx.split(",");
        const faults = [];
        const faultAs = [];
        for(let i = 0 ; i < arr.length ; i++) {
          const fault = arr[i];
          faults.push(fault);
        }
        for(let i = 0 ; i < arrS.length ; i++) {
          const faultA = arrS[i];
          faultAs.push(faultA);
        }
        row.sybm = faults.join("|");
        row.yalx = faultAs.join("|");
        const idsArr = [];
        this.hazardTags.forEach(item => {
          idsArr.push(item.id);
        });
        const updateData = {
          id: row.id,
          yabh: row.yabh,
          yamc: row.yamc,
          sybm: row.sybm,
          yalx: row.yalx,
          yajb: row.yajb,
          yarq: row.yarq,
          bxr: row.bxr,
          bxbm: row.bxbm,
          fbssrq: row.fbssrq,
          yafj: row.yafj,
          bz: row.bz,
          bladeDeptId: row.bladeDeptId,
          tenantId: row.tenantId,
          createUser: row.createUser,
          createDept: row.createDept,
          createTime: row.createTime,
          zdwxybh: row.zdwxybh,
          zdwxymc: row.zdwxymc,
          spr: row.spr,
          wxygl: "",
          ids: ""
        };
        updateData.wxygl = idsArr.join(",");
        updateData.ids = idsArr.join(",");
        update(updateData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return remove(row.id);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (type === "edit") {
          if (this.form.ywzt === 9) {
            this.$message.warning("当前预案已作废!");
            return;
          }
          if (this.form.ywzt === 2 || this.form.ywzt === 3) {
            this.$message.warning("当前预案不可编辑!");
            return;
          }
        }
        this.yafjFileList = [];
        this.hazardTagsErr = false;
        this.hazardTags = [];
        this.selectHazard = {};
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            const arr =  res.data.data.yalx.split("|");
            const arrS = res.data.data.sybm.split("|");
            const faults = [];
            const faultAs = [];
            for(let i = 0 ; i < arr.length ; i++) {
              const fault = arr[i];
              faults.push(fault);
            }
            for(let i = 0 ; i < arrS.length ; i++) {
              const faultA = arrS[i];
              faultAs.push(faultA);
            }
            res.data.data.yalx = faults.join(",");
            res.data.data.sybm = faultAs.join(",");
            this.form = res.data.data;
            this.form.hazardDataSiteInfos.forEach(item => {
              this.hazardTags.push(item);
              this.selectHazard[item.id] = item;
            });
            if (type === "edit") {
              this.yafjFileList.push({
                name: this.form.bladeFile.fileName,
                response: {
                  code: 200,
                  success: true,
                  msg: "操作成功",
                  data: this.form.bladeFile
                }
              });
            }
          });
        }else{
          getYabhByCustom().then(res => {
            this.form.yabh = res.data.data;
          })
        }
        done();
      },

      /**
       * 上传预案附件
       */
      // 上传附件前
      beforeUploadYAFJ() {
        const isLimit = this.yafjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传附件成功
      uploadYAFJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.yafjFileList = fileList;
        this.form.yafj = response.data.id;
      },

      // 删除附件
      handleRemoveYAFJ(file, fileList) {
        this.yafjFileList = fileList;
        this.form.yafj = "";
      },

      /**
       * 上传变更附件
       */
      // 上传变更附件前
      beforeUploadBGFJ(file) {
        console.log(file);
        let isLimit = this.bgfjFileList.length + 1 <= 1;
        if (!isLimit) {
          this.$message.warning("只能选择一个附件!");
        }
        return isLimit;
      },

      // 上传变更附件成功
      uploadBGFJSuccess(response, file, fileList) {
        if (response.code !== 200 || response.success !== true) {
          return;
        }
        this.bgfjFileList = fileList;
        this.updateObj.yafj = response.data.id;
      },

      // 删除变更附件
      handleRemoveBGFJ(file, fileList) {
        this.bgfjFileList = fileList;
        this.updateObj.yafj = "";
      },

      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleExport() {
        this.$confirm("是否导出应急预案管理信息?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          window.open(`/api/emerPlan/plan/export-plan?${this.website.tokenHeader}=${getToken()}`);
        });
      },
      // 点击作废按钮
      handleVoid() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据作废?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          return invalidPlan(this.ids);
        }).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
      }
    }
  };
</script>

<style lang="scss">
  .hazardManager {
    .el-form-item__label {
      width: 100px !important;
    }
    .avue-form__row {
      .el-form-item__content {
        margin-left: 100px !important;
      }
    }
  }

</style>

<style lang="scss" scpoed>
  .emerPlan {
    .avue-crud {
      .avue-crud__search {
        .avue-form__row:nth-child(1) {
          .el-form-item__label {
            text-align: unset;
            width: 90px !important;
          }

          .el-form-item__content {
            margin-left: 90px !important;
          }
        }
      }
    }

    .enclosure_div {
      a {
        font-size: 12px;
        color: #409eff;

        i {
          margin-right: 5px;
        }
      }
    }
  }

  .avue-dialog {
    .el-dialog {
      .avue-group {
        .avue-form__group {
          .el-form-item {
            .el-form-item__label {
              width: 110px !important;
            }

            .el-form-item__content {
              margin-left: 110px !important;
            }
          }
        }
      }
    }
  }

  .hazard_error {
    color: #F56C6C;
    font-size: 12px;
    margin-left: 5px;
  }

  .hazard_point_list {
    margin-top: 5px;

    .el-tag {
      margin-right: 5px;
    }
  }

  .approval_modify_dialog {
    .avue-form__menu--center {
      text-align: center;
    }
  }

  .modify_record_footer {
    text-align: center;
    margin-top: 15px;

    .el-button {
      width: 100px;
      height: 35px;
    }
  }

  .modify_record_dialog {
    .avue-crud__menu,
    .avue-crud__pagination {
      display: none;
    }
  }

</style>
